package ru.niir.goodfil.ui.utils;

import ru.niir.goodfil.ui.SecurityBean;
import ru.niir.goodfil.ui.SessionBean;

import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Волков Олег on 12.11.14.
 */
public class SecurityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpSession session = null;
        session = httpServletRequest.getSession(false);
        if(session != null){
            SecurityBean securityBean = (SecurityBean) session.getAttribute("SecurityBean");
            if(securityBean != null){
                if(!securityBean.getIsAuthorized()){
                    httpServletResponse.sendRedirect("/Zip1001/ClientGoodsPage.jsf");
                    return;
                }
            }
            chain.doFilter(request, response);
        }
        if(session == null){
            httpServletResponse.sendRedirect("/Zip1001/ClientGoodsPage.jsf");
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
